package cn.tradewin.pmp.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.tradewin.pmp.persist.client.MCustomerMapper;
import cn.tradewin.pmp.persist.client.MDeptMapper;
import cn.tradewin.pmp.persist.model.MCustomer;
import cn.tradewin.pmp.services.CustomerManageService;

public class CustomerManageServiceImpl implements CustomerManageService {

	private final SqlSessionFactory sqlSessionFactory;
	
	public CustomerManageServiceImpl(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}
	
	
	@Override
	public int AddCustomer(MCustomer customer) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MCustomerMapper mapper = session.getMapper(MCustomerMapper.class);
			int iCount = mapper.insertSelective(customer);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int updCustomer(MCustomer customer) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MCustomerMapper mapper = session.getMapper(MCustomerMapper.class);
			int iCount = mapper.updateByPrimaryKey(customer);
			if (iCount > 0) {
				session.commit();
			}
			return iCount;
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public int DelCustomers(List<String> customers) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MCustomerMapper mapper = session.getMapper(MCustomerMapper.class);
			int iDels = mapper.deleteByPrimaryKeyList(customers);
			if (iDels > 0) {
				session.commit();
			}
			return iDels;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public List<MCustomer> getAllCustomers() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MCustomerMapper mapper = session.getMapper(MCustomerMapper.class);
			return mapper.selectByExample(null);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public MCustomer findCustomerByPrimary(String customerNo) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			MCustomerMapper mapper = session.getMapper(MCustomerMapper.class);
			return mapper.selectByPrimaryKey(customerNo);
		} catch (Exception e) {
			session.rollback();
			throw new RuntimeException(e.getMessage());
		}
	}

}
